<?php

namespace backend\models;

use common\helpers\Constant;
use common\models\User as BaseUser;
use Yii;
use yii\data\ActiveDataProvider;
use yii\rbac\Role;

/**
 *  用户模型
 */
class User extends BaseModel
{

    const SCENARIO_SIGN_UP = 'SCENARIO_SIGN_UP';
    const SCENARIO_RESET_PASSWORD = 'SCENARIO_RESET_PASSWORD';

    public $id;
    public $role;
    public $username;
    public $password;

    public function attributeLabels()
    {
        return [
        ];
    }

    /**
     * set scenarios
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_SIGN_UP => ['role', 'username', 'password'],
            self::SCENARIO_RESET_PASSWORD => ['id', 'password'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'role', 'username', 'password'], 'required'],
        ];
    }

    public function getList()
    {
        $query = BaseUser::find()
            ->where(['status' => BaseUser::STATUS_ACTIVE]);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => Constant::PAGE_SIZE,
            ],
            'sort' => [
            ],
        ]);
        return $dataProvider;
    }

    /**
     * @return bool
     * @throws \Exception
     */
    public function signUp()
    {
        if (!$this->validate()) {
            return false;
        }
        $roleArr = BaseUser::ROLE_ARR;
        $roleArr = array_flip($roleArr);
        $user = new BaseUser();
        $user->username = $this->username;
        $user->status = BaseUser::STATUS_ACTIVE;
        $user->role = $roleArr[$this->role];
        $user->setPassword($this->password);
        $user->generateAuthKey();
        if ($user->save(false)) {
            $role = new Role();
            $role->name = isset(BaseUser::ROLE_ARR[$user->role]) ? BaseUser::ROLE_ARR[$user->role] : '未知';
            Yii::$app->authManager->assign($role, Yii::$app->db->getLastInsertID());
        }
        return true;
    }

    public function resetPassword()
    {
        if (!$this->validate()) {
            return false;
        }
        $user = BaseUser::findOne($this->id);
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save(false);
        return true;
    }
}
